import request from "@/utils/Request";

const downLoad = (url, param, errorMsg = '导出失败')=> {
  request.post(url, param, {responseType: 'blob'}).then(response => {
    if (response?.data === '401') {
      this.$router.push({path: '/Login'});
    }
    const realFileName = response.headers['content-disposition'].match(/fileName=(.*)/)[1];
    const blob = new Blob([response.data], {type: 'application/octet-stream'});
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(blob, decodeURI(realFileName))
    } else {
      const blobURL = window.URL.createObjectURL(blob)
      const tempLink = document.createElement('a')
      tempLink.style.display = 'none'
      tempLink.href = blobURL
      tempLink.setAttribute('download', decodeURI(realFileName))
      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank')
      }
      document.body.appendChild(tempLink)
      tempLink.click()
      document.body.removeChild(tempLink)
      window.URL.revokeObjectURL(blobURL)
    }
  }).catch(err => {
    this.$message({type: 'error', message: errorMsg});
    console.log(err)
  });
};

export {downLoad};